import React, { Component } from 'react'
import { Modal, Popover, Form, Input, message } from 'antd'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import BreadCrumb from '@/components/BreadCrumb'
import { TOKEN, USER_INFO, PUBLIC_KEY } from '@/Utils/CONST'
import regexp from '@/Utils/regexp'
import { cryptoData } from '@/Utils/common'

import './index.less'

export default class HeaderComp extends Component {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      poolData: [],
    }
  }

  logoutTip = () => {
    const socket = this.props.SocketModel.getSocket()
    socket && socket.close()
    Modal.confirm({
      content: '确认退出登录吗?',
      onOk: async() => {
        const { code } = await request().post(address.logout)
        if (code === 200) {
          message.success('退出成功')
          localStorage.removeItem(USER_INFO)
          localStorage.removeItem(TOKEN)
          localStorage.removeItem(PUBLIC_KEY)
          this.props.history.replace({
            pathname: '/login',
          })
        }
      },
    })
  }

  onFinish = async(values) => {
    const { code } = await request().post(address.account.modifyPwd, cryptoData(JSON.stringify(values), localStorage.getItem(PUBLIC_KEY)))
    if (code === 200) {
      message.success('密码修改成功')
      this.setState({
        visible: false,
      })
      setTimeout(() => {
        this.props.history.replace('/login')
      }, 500)
    }
  }

  render() {
    const userInfo = JSON.parse(localStorage.getItem(USER_INFO) || '{}')
    const { visible } = this.state
    return (
      <div className="basic-header">
        <BreadCrumb {...this.props} />

        <Popover
          placement="bottom"
          overlayClassName="handle-popover"
          content={
            <div className="popover-handle-content">
              <p
                onClick={() => this.setState({ visible: true })}
                className="popover-handle-item primary cursor">
                修改密码
              </p>
              <p onClick={this.logoutTip} className="popover-handle-item primary cursor" >
                退出登录
              </p>
            </div>
          }
        >
          <div className="header-list cursor">
            <div style={{ marginRight: 8 }}>
              <img src={require('@/images/dashboard/me.svg')} alt="" />
            </div>
            <div>{userInfo && userInfo.username}
            </div>
          </div>
        </Popover>
        {/* 修改密码 */}
        <Modal centered
          destroyOnClose
          title={`修改密码`}
          onCancel={() => this.setState({ visible: false })}
          visible={visible}
          onOk={() => this.form && this.form.submit()}
          maskClosable={false}>
          <Form
            autoComplete="false"
            {...{
              labelCol: { span: 6 },
              wrapperCol: { span: 16 },
            }}
            onFinish={this.onFinish}
            ref={c => this.form = c}
          >
            <Form.Item
              label="原密码:"
              name="oldPwd"
              validateFirst
              rules={[{ required: true, message: '请输入原密码' }]}
            >
              <Input.Password maxLength={30} placeholder="请输入原密码" />
            </Form.Item>
            <Form.Item
              label="新密码:"
              name="newPwd"
              validateFirst
              rules={[
                { required: true, message: '请输入新密码' },
                {
                  type: 'string',
                  min: 8,
                  pattern: regexp._pwd,
                  message: '密码须为8位以上字母数字与特殊字符的组合',
                },
              ]}
            >
              <Input.Password maxLength={30} placeholder="请输入新密码" />
            </Form.Item>
            <Form.Item
              label="确认新密码:"
              name="confirm_pwd"
              validateFirst
              rules={[
                { required: true, message: '请输入新密码' },
                {
                  type: 'string',
                  min: 8,
                  pattern: regexp._pwd,
                  message: '密码须为8位以上字母数字与特殊字符的组合',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (getFieldValue('newPwd') === value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('密码两次输入不一致'))
                  },
                }),
              ]}
            >
              <Input.Password maxLength={30} placeholder="请输入新密码" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}

